//
//  CompanyItemView.swift
//  AirlineReservation
//
//  Created by Kevin on 2020/2/19.
//  Copyright © 2020 Kevin. All rights reserved.
//

import UIKit

class CompanyItemView: UIView {
    
    
    public var companyExpenses:[CompanyExpenseInfo]? {
        didSet {
            updateLayout()
        }
    }
    
    // 滑动
    private var scrollview = UIScrollView()
    // 回调
    public var complete:((_ item:CompanyExpenseInfo) ->Void)?
    
    override func layoutSubviews() {
        guard let companys = companyExpenses else {
            return
        }
        // 高度
        var tempHeight:CGFloat = 0
        for i in 0..<companys.count {
            let subView = SubCompanyItemView()
            subView.company = companys[i]
            subView.layer.cornerRadius = 5
            subView.backgroundColor = UIColor.white
            subView.frame = CGRect(x: MARGIN, y: tempHeight, width: frame.width - MARGIN * 2, height: MARGIN90)
            scrollview.addSubview(subView)
            // 编辑图片
            let editView = UIButton()
            editView.tag = i
            let editX = frame.width - MARGIN70
            editView.setImage(UIImage(named: "edit_15x15"), for: .normal)
            editView.frame = CGRect(x: editX, y: tempHeight, width: MARGIN50, height: MARGIN50)
            scrollview.addSubview(editView)
            // 记录高度
            tempHeight = subView.frame.maxY + MARGIN15
            // 添加点击事件
            editView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(clickPersonItem(ui:))))
        }
        addSubview(scrollview)
        // 设置scrollview属性
        scrollview.showsVerticalScrollIndicator = false
        scrollview.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
        scrollview.contentSize = CGSize(width: frame.width, height: tempHeight + MARGIN30)
    }
    
    @objc func clickPersonItem(ui:UITapGestureRecognizer) -> Void {
        if let callback = complete,let index = ui.view?.tag {
            callback(companyExpenses![index])
        }
    }
    
    class SubCompanyItemView: UIView {
        
        // 抬头
        private let label = UILabel(title: "", color: COLOR_NICE, size: 17)
        // 税号
        private let duty = UILabel(title: "", color: UIColor.gray, size: 13)
        
        public var company:CompanyExpenseInfo? {
            didSet {
                label.text = company?.title
                duty.text = "税号 \(company!.duty!)"
            }
        }
        
        override func layoutSubviews() {
            // 抬头
            let labelW = frame.width - MARGIN20
            label.frame = CGRect(x: MARGIN10, y: MARGIN20, width: labelW, height: MARGIN)
            addSubview(label)
            // 税号
            duty.frame = CGRect(x: MARGIN10, y: label.frame.maxY + MARGIN, width: labelW, height: MARGIN)
            addSubview(duty)
        }
    }
}
